<?php

namespace App\Models\Game\Log;

use App\Models\Game\Model;
use App\Models\Game\Platform\Org;
use App\Models\Elasticsearch\Log\Cost as EsCost;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Cost extends Model
{

    /**
     * 数据表名称
     *
     * @var string
     */
    protected $table = 't_log_cost';

    /**
     * 进行类型转换的字段
     *
     * @var array
     */
    protected $casts = [
        'usd' => 'array',
    ];

    /**
     * 获得平台信息
     *
     * @return BelongsTo
     */
    public function org(): BelongsTo
    {
        return $this->belongsTo(Org::class, 'plat_code', 'code')->withTrashed();
    }

    /**
     * 获取一条日志【来源ID】
     *
     * @param $sourceId
     * @return array|null
     */
    protected function findBySourceId($sourceId): ?array
    {
        if (!config('elasticsearch.default')) {
            $cost = $this->newQuery()->where('source_id', $sourceId)->first();

            return $cost ? $cost->toArray() : null;
        } else {
            return EsCost::findBySourceId($sourceId);
        }
    }
}
